<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="参数名称" prop="settingName">
            <el-input v-model.trim="form.settingName" :disabled="updateModel" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="参数描述" prop="settingLabel">
            <el-input v-model.trim="form.settingLabel" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="备注">
            <el-input v-model.trim="form.remark" />
          </el-form-item>
        </el-col>
        <template v-if="updateModel == true">
          <!-- <el-row>? -->
          <el-col :span="10">
            <el-form-item label="创建人">
              <el-input :disabled="true" :value="form.createBy" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="创建时间">
              <el-input :disabled="true" :value="form.createTime" />
            </el-form-item>
          </el-col>
          <!-- </el-row> -->
          <!-- <el-row> -->
          <el-col :span="10">
            <el-form-item label="修改人"> <el-input :disabled="true" :value="form.updateBy" /> </el-form-item></el-col>
          <el-col :span="10">
            <el-form-item label="修改时间"> <el-input :disabled="true" :value="form.updateTime" /> </el-form-item></el-col>
          <!-- </el-row> -->
        </template>
        <el-col :span="20">
          <el-form-item label="">
            <el-button type="primary" @click="showAddLogModel()">参数配置</el-button>
          </el-form-item>
        </el-col>
        <el-col v-if="isWidgetForms" :span="20">
          <avue-form ref="avueForm" v-model="widgetModels" :option="widgetFormPreview" :upload-before="uploadBefore" :upload-after="uploadAfter" :upload-preview="uploadPreview" :upload-error="uploadError" :upload-delete="uploadDelete" class="preview-form" />
        </el-col>
      </el-row>
      <el-form-item style="width: 100%">
        <el-button v-if="!isFind" type="primary" size="medium" @click="onSubmit">保存</el-button>
        <el-button v-else disabled type="primary" size="medium" @click="onSubmit">保存</el-button>
        <el-button size="medium" @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>

    <!--弹出配置参数的弹框-->
    <LgModal v-if="isShowModalSearchLog" v-show="isModalSearchLog" ref="Modal" status-text="自定义表单" background-color="#fff" content-text="index.vue" alert="1" @closeModal="closeModal" @button="closeModal">
      <avue-form-design ref="formDesign" style="height: 86vh" :options="options" :show-github-star="false" :toolbar="toolbar" :include-fields="includeFileds" storage>
        <template slot="toolbar">
          <el-button type="text" icon="el-icon-download" @click="handleSubmit">生成表单</el-button>
        </template>
      </avue-form-design>
    </LgModal>
  </div>
</template>

<script>
import { authSetting, queryById, authSettingEdit, settingPageList, uploadImg } from '@/api/system-set'
import LgModal from './LgModal.vue'
import axios from 'axios'
export default {
  components: {
    LgModal,
  },
  data() {
    return {
      form: {
        settingId: null,
        settingName: '',
        settingLabel: '',
        settingType: '',
        settingValue: '',
        settingForm: '',
        remark: '',
        createdBy: '',
        createdTime: null,
        updatedBy: '',
        updatedTime: null,
      },
      // 参数配置的data
      isShowModalSearchLog: false,
      isModalSearchLog: false,
      toolbar: ['clear'],
      includeFileds: ['group', 'dynamic', 'title', 'input', 'password', 'textarea', 'number', 'url', 'array', 'radio', 'checkbox', 'select', 'cascader', 'tree', 'upload', 'year', 'month', 'week', 'date', 'time', 'datetime', 'daterange', 'timerange', 'datetimerange', 'ueditor', 'switch', 'rate', 'slider'],
      isWidgetForms: false,
      options: {},
      widgetFormPreview: {
        column: [],
      },
      widgetForm: {},
      widgetModels: {},
      addForm: {
        settingValue: '',
        settingForm: '',
      },
      optionsColumn: [],

      rules: {
        settingName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
        settingLabel: [{ required: true, message: '请输入参数描述', trigger: 'blur' }],
        settingType: [{ required: true, message: '请输入参数类型', trigger: 'change' }],
        settingValue: [{ required: true, message: '请输入参数值', trigger: 'blur' }],
      },
      updateData: {},
      isFind: true,
    }
  },
  computed: {
    updateModel() {
      return this.$route.query.id != null
    },
    formItem() {
      return {
        type: this.form.settingType,
        label: this.form.settingLabel,
        name: this.form.settingName,
        required: true,
        placeholder: '',
        accessKey: {},
      }
    },
    formItemData() {
      return { [this.form.settingName]: this.form.settingValue }
    },
  },
  created() {
    var id = this.$route.query.id
    var accessKey = this.$route.query.accessKey
    this.isFind = this.$route.query.val
    if (id != null) {
      this.accessKey = accessKey
      this.form.id = id
      this.queryDetail(this.form.id, accessKey)
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    eachChange(val) {},
    async queryByPage() {
      const that = this
      const res = await settingPageList({ pageNumber: 1, pageSize: 10, settingName: this.name })
      if (res.code != '200') return
      this.form = res.data.records[0]
    },
    async queryDetail(id, accessKey) {
      const that = this
      const res = await queryById({ id: id, accessKey: accessKey })
      if (res.code != '200') return
      this.form = res.data
      this.updateData = that.deepClone(this.form)
      this.isWidgetForms = true
      this.widgetModels = JSON.parse(this.updateData.settingValue)
      if (this.updateData.settingForm != undefined && this.updateData.settingForm != '') {
        this.widgetFormPreview = JSON.parse(this.updateData.settingForm)
      }
      this.options = this.widgetFormPreview
    },
    // 关闭模态框
    closeModal() {
      this.isModalSearchLog = false
      this.isShowModalSearchLog = false
    },
    // 打开模态框
    showAddLogModel() {
      this.isShowModalSearchLog = true
      this.isModalSearchLog = true
      this.$nextTick(() => {
        let oldOptions = {}
        oldOptions = this.options
        if (oldOptions.column.length > 0) {
          this.$refs.formDesign.handleFieldClick(oldOptions.column[0])
        }
      })
    },
    // 保存生成的JSON
    handleSubmit() {
      this.$refs.formDesign.getData().then((data) => {
        this.optionsColumn = []
        this.widgetFormPreview.column = []
        this.addForm.settingForm = JSON.stringify(data)
        this.optionsColumn = data.column
        this.widgetFormPreview.column = this.optionsColumn
        this.widgetForm = data
        this.isWidgetForms = true
        if (!this.widgetForm.column || this.widgetForm.column.length == 0) this.$message.error('没有需要展示的内容')
        else {
          this.$refs.formDesign.transformToAvueOptions(this.widgetForm).then((data) => {
            this.widgetFormPreview = data
          })
        }
        this.closeModal()
      })
    },
    // 删除图片
    uploadDelete(column, path) {
      const url = path.url
      if (url) {
        const splitter = '/file/'
        const split = url.split(splitter)
        const element = split[1]
        const pathUrl = element.split('/')
        const id = pathUrl[0]
        const fileName = pathUrl[1]
        return new Promise((resolve, reject) => {
          this.$confirm(`是否确认删除名称为${fileName}`, '提示', {
            confirmButtonText: '确 定',
            cancelButtonText: '取 消',
            type: 'warning',
          })
            .then(() => {
              axios.post('/file/delete', { id: id })
              resolve()
            })
            .catch(() => {
              reject()
              this.$message({
                type: 'info',
                message: '已取消删除',
              })
            })
        })
      }
    },
    // 上传前
    async uploadBefore(file, done, loading, column) {
      const fileData = new FormData()
      fileData.append('file', file, file.name)
      const { code, data } = await uploadImg(fileData)
      if (code != '200') return
      console.log(this.$refs.avueForm.uploadPreview)
      // this.$refs.avueForm.handleSuccess(data)
    },
    // 上传后
    uploadAfter(res, done, loading, column) {
      console.log(res, column, loading)
      // console.log("===============uploadAfter================");
      // console.log(res)
      done()
    },
    uploadError(error, column) {
      this.$message.error('上传失败')
    },

    // 上传后进行点击预览
    uploadPreview(file, column, done) {
      // uploadImg(file).then((response) => {
      //   console.log(response)
      //   done()
      // })
      done()
    },
    deepClone(source) {
      if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'shallowClone')
      }
      const targetObj = source.constructor === Array ? [] : {}
      Object.keys(source).forEach((keys) => {
        if (source[keys] && typeof source[keys] === 'object') {
          targetObj[keys] = this.deepClone(source[keys])
        } else {
          targetObj[keys] = source[keys]
        }
      })
      return targetObj
    },
    onSubmit() {
      this.addForm.settingValue = JSON.stringify(this.widgetModels)
      this.$refs['form'].validate(async(valid) => {
        if (!valid) {
          return
        }
        if (this.$route.query.id) {
          // 为更新除表单之外的值
          this.updateData.settingLabel = this.form.settingLabel
          this.updateData.remark = this.form.remark
          this.updateData.settingValue = this.addForm.settingValue
          this.updateData.settingForm = this.addForm.settingForm
          authSettingEdit(this.updateData).then((response) => {
            if (response.repCode == '0000') {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 2 * 1000,
              })
              this.goBack()
            }
          })
          // const { code } = await authSettingEdit(this.updateData)
          // if (code != '200') return
          // this.$message({
          //   message: '操作成功',
          //   type: 'success',
          //   duration: 2 * 1000,
          // })
          // this.goBack()
        } else {
          this.form.settingValue = this.addForm.settingValue
          this.form.settingForm = this.addForm.settingForm
          const data = this.deepClone(this.form)
          authSetting(data).then((response) => {
            if (response.repCode == '0000') {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 2 * 1000,
              })
              this.goBack()
            }
          })
          // const { code } = await authSetting(data)
          // if (code != '200') return
          // this.$message({
          //   message: '操作成功',
          //   type: 'success',
          //   duration: 2 * 1000,
          // })
          // this.goBack()
        }
      })
    },
  },
}
</script>

<style scoped lang="scss">
.line {
  text-align: center;
}
.parameter-add {
  /deep/.el-textarea .el-textarea__inner {
    min-height: 400px !important;
    max-height: 600px !important;
  }
}
</style>
